package com.evision.webcrawler.baidu.parser;

import com.evision.webcrawler.baidu.Parser;
import com.evision.webcrawler.baidu.RequestUrl;
import com.evision.webcrawler.baidu.url.ImageInfoUrl;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.BlockingQueue;

/**
 * 
 * @author xiang
 * 百度图像链接下载Parser
 * 下载图像链接到本地文件目录
 *
 */
public class BaiduImageDowloader implements Parser{
	private static BaiduImageDowloader instance;
	private final String basePath;
	private final String extension = ".jpg&.png";										//扩展名条件,限定下载文件的扩展名
	private BaiduImageDowloader(String basePath){
		this.basePath = basePath;
	}
	
	public static BaiduImageDowloader getInstance(String basePath){
		if(instance == null)
			instance = new BaiduImageDowloader(basePath);
		return instance;
	}
	
	public void parser(HttpResponse response, BlockingQueue<RequestUrl>[] outQueue,
					   RequestUrl args) {
		File f = new File(this.basePath);
		if(!f.exists()){
			f.mkdirs();
		}
		ImageInfoUrl info = (ImageInfoUrl)args;
		if(response.getStatusLine().getStatusCode() == 200){						//请求成功则进行解析
			int tp = info.getUrl().lastIndexOf(".");
			if(tp != -1){
				String tail = info.getUrl().substring(tp,info.getUrl().length());	//扩展名
				if(extension.contains(tail)){										//如果扩展名包含则下载
					String filePath = 	this.basePath + "/" + info.getWord().getWord();
					File fp = new File(filePath);
					if(!fp.exists()){
						fp.mkdirs();
					}
					String path = filePath + "/" +UUID.randomUUID().toString()+tail;
					fp = new File(path);
			    	HttpEntity entity = response.getEntity();
			    	try{
				    	FileOutputStream fout = new FileOutputStream(path);
				    	try{
				    		entity.writeTo(fout);
				 			fout.close();
				 		}catch(IOException e){
				 			fp.delete();
				 			e.printStackTrace();
				 		}finally{
				 			try{
				 				fout.close();
				 			}catch(IOException e2){
				 				e2.printStackTrace();
				 			}
				 		}
			    	}catch(FileNotFoundException e1){
			    		e1.printStackTrace();
			    	}
				}
			}
		}
	}
}
